#!/usr/local/bin/ruby

require 'rubygems'
require 'xmlsimple'

@home_dir = File.expand_path("~")
require File.join(@home_dir, 'backpack')

def format_time(t)
  t.strftime("%B %d, %Y at %I:%M %p")
end

command = ARGV.shift

home_dir = ENV['HOME']
config_path = File.join(home_dir, '.backpack.yml')
if !File.exist?(config_path) && ('setup' != command)
  raise StandardError, "Missing config file: ~/.backpack.yml"
end

if 'setup' != command
  conf = YAML.load_file(config_path)
  conf = conf['backpack']
  @bp = Backpack.new(conf['username'], conf['api_key'])
  @bp.page_id = conf['home_page_id']
end

case command
when 'list', 'todo', 'todos'
  @todo = []
  @completed = []
  res = @bp.list_items
  list = res["items"].first['item']
  list.each do |item|
    if 'false' == item['completed'] 
      @todo << item['content']
    else
      @completed << item['content']
    end
  end
  
  puts "\nTODO:\n\n"
  @todo.each do |t|
    puts " * #{t}"
  end
  puts "\nCompleted: \n\n"
  @completed.each do |t|
    puts " * #{t}"
  end
  puts "\n"
when 'add'
  todo = ARGV.shift
  if todo.nil? || todo.empty?
    puts "Specify a todo like: ruby todo.rb add \"Global domination\""; exit
  end
  @bp.create_item(todo)
  puts "\nAdded TODO: #{todo}\n\n"
when 'pages'
  res = @bp.list_pages
  list = res['pages'].first['page']
  puts "\nBackpack Pages - Title (page_id): \n\n"
  list.each do |item|
    puts " * " + item['title'] + " (#{item['id']})"
  end
  puts "\n"
when 'reminders'
  res = @bp.list_reminders
  list = res['reminders'].first['reminder']
  puts "\nReminders: \n\n"
  list.each do |item|
    t = DateTime.parse(item['remind_at']).
    puts " * #{t} - #{item['content']}"
  end
  puts "\n"
when 'remind'
  remind_at = ARGV.shift
  reminder = ARGV.shift
  last = remind_at.split('').last.strip

  unless ['d', 'h'].include?(last)
    puts "Reminder time must be in hours or days, i.e.: todo remind 7h \"Foo\"  or todo remind 5d \"Bar\""; exit
  end
  
  if 'h' == last
    hours = remind_at.gsub('h', '').to_i
    remind_at = Time.now + (hours * 60 * 60)
  elsif 'd' == last
    days = remind_at.gsub('d', '').to_i
    remind_at = Time.now + (days * 60 * 60 * 24)
  end
  formatted = remind_at.strftime("%Y-%d-%m %H:%M")
  puts "Remind at: #{remind_at.to_s} :: #{formatted}"
  @bp.create_reminder(reminder, formatted)
when 'setup'
  if File.exist?(config_path)
    puts "Your config file already exists."; exit
  end
  conf = <<CONF
backpack:
  username: 
  api_key:
  # To find your main Backpack page ID, try 'todo pages' once you've set your username & api_key here.
  home_page_id: 
CONF
  File.open(config_path, 'w') do |f|
    f.puts(conf)
  end
  puts "\nNow edit your ~/.backpack.yml file in your favorite text editor. :)"
else
  @usage = <<EOF

Usage:

 todo setup                               -- setup your ~/.backpack.yml file
 todo pages                               -- list your Backpack pages
 todo list                                -- list your main TODOs
 todo add "Buy milk & kahlua"             -- add a new TODO list item
 todo reminders                           -- list reminders
 todo remind 6h "Kung fu lessons"         -- add a reminder in 6 hours
  or todo remind 5d "Trip to Portland"    -- add a reminder in 5 days
  
EOF
  puts @usage
end
